package com.socks.sample.slice;

import com.socks.library.KLog;
import com.socks.sample.ResourceTable;
import com.socks.sample.TestTraceUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import ohos.utils.IntentConstants;
import ohos.utils.net.Uri;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Properties;

public class MainAbilitySlice extends AbilitySlice implements Component.ClickedListener {

    private static final String LOG_MSG = "KLog is a so cool Log Tool!";
    private static final String TAG = "KLog";
    private static final String URL_XML = "https://raw.githubusercontent.com/ZhaoKaiQiang/KLog/master/app/src/main/And" + "roidManifest.xml";
    private static String XML = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><!--  Copyright w3school.com.cn --><note><to>George</to><from>John</from><heading>Reminder</heading><body>Don't forget the meeting!</body></note>";
    private static String JSON;
    private static String JSON_LONG;
    private static String STRING_LONG;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
//        HiLogLabel label  = new HiLogLabel(HiLog.LOG_APP, 0x00201, "main");
//        HiLog.debug(label,"123","123456");
        initData();
        Button Id_logDebug = (Button) findComponentById(ResourceTable.Id_logDebug);
        Button Id_log = (Button) findComponentById(ResourceTable.Id_log);
        Button Id_logWithNull = (Button) findComponentById(ResourceTable.Id_logWithNull);
        Button Id_logWithMsg = (Button) findComponentById(ResourceTable.Id_logWithMsg);
        Button Id_logWithLong = (Button) findComponentById(ResourceTable.Id_logWithLong);
        Button Id_logWithTag = (Button) findComponentById(ResourceTable.Id_logWithTag);
        Button Id_logWithParams = (Button) findComponentById(ResourceTable.Id_logWithParams);
        Button Id_logWithJson = (Button) findComponentById(ResourceTable.Id_logWithJson);
        Button Id_logWithLongJson = (Button) findComponentById(ResourceTable.Id_logWithLongJson);
        Button Id_logWithJsonTag = (Button) findComponentById(ResourceTable.Id_logWithJsonTag);
        Button Id_logWithFile = (Button) findComponentById(ResourceTable.Id_logWithFile);
        Button Id_logWithXml = (Button) findComponentById(ResourceTable.Id_logWithXml);
        Button Id_logWithXmlFromNet = (Button) findComponentById(ResourceTable.Id_logWithXmlFromNet);
        Button Id_logTraceStack = (Button) findComponentById(ResourceTable.Id_logTraceStack);
        Text Id_github = (Text) findComponentById(ResourceTable.Id_github);
        Text Id_blog = (Text) findComponentById(ResourceTable.Id_blog);

        Id_logDebug.setClickedListener(this);
        Id_log.setClickedListener(this);
        Id_logWithNull.setClickedListener(this);
        Id_logWithMsg.setClickedListener(this);
        Id_logWithLong.setClickedListener(this);
        Id_logWithTag.setClickedListener(this);
        Id_logWithParams.setClickedListener(this);
        Id_logWithJson.setClickedListener(this);
        Id_logWithLongJson.setClickedListener(this);
        Id_logWithJsonTag.setClickedListener(this);
        Id_logWithFile.setClickedListener(this);
        Id_logWithXml.setClickedListener(this);
        Id_logWithXmlFromNet.setClickedListener(this);
        Id_logTraceStack.setClickedListener(this);
        Id_github.setClickedListener(this);
        Id_blog.setClickedListener(this);

    }

    private void initData() {
        ohos.global.resource.ResourceManager resManager = getResourceManager();
        try {
            JSON_LONG = resManager.getElement(ResourceTable.String_json_long).getString();
            JSON = resManager.getElement(ResourceTable.String_json).getString();
            STRING_LONG = resManager.getElement(ResourceTable.String_string_long).getString();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotExistException e) {
            e.printStackTrace();
        } catch (WrongTypeException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            case ResourceTable.Id_logDebug:
                logDebug();
                break;
            case ResourceTable.Id_log:
                log();
                break;
            case ResourceTable.Id_logWithNull:
                logWithNull();
                break;
            case ResourceTable.Id_logWithMsg:
                logWithMsg();
                break;
            case ResourceTable.Id_logWithLong:
                logWithLong();
                break;
            case ResourceTable.Id_logWithTag:
                logWithTag();
                break;
            case ResourceTable.Id_logWithParams:
                logWithParams();
                break;
            case ResourceTable.Id_logWithJson:
                logWithJson();
                break;
            case ResourceTable.Id_logWithLongJson:
                logWithLongJson();
                break;
            case ResourceTable.Id_logWithJsonTag:
                logWithJsonTag();
                break;
            case ResourceTable.Id_logWithFile:
                logWithFile();
                break;
            case ResourceTable.Id_logWithXml:
                logWithXml();
                break;
            case ResourceTable.Id_logWithXmlFromNet:
                logWithXmlFromNet();
                break;
            case ResourceTable.Id_logTraceStack:
                logTraceStack();
                break;
            case ResourceTable.Id_github:
                initWeb("https://github.com/ZhaoKaiQiang/KLog");
                break;
            case ResourceTable.Id_blog:
                initWeb("http://blog.csdn.net/zhaokaiqiang1992");
                break;
            default:
                break;
        }
    }

    public void logTraceStack() {
        TestTraceUtil.testTrace();
    }

    public void logDebug() {
        KLog.debug();
        KLog.debug("This is a debug message");
        KLog.debug("DEBUG", "params1", "params2", this);
    }

    public void log() {
        KLog.d();
        KLog.i();
        KLog.w();
        KLog.e();
        KLog.f();
    }

    public void logWithNull() {
        KLog.d(null);
        KLog.i(null);
        KLog.w(null);
        KLog.e(null);
        KLog.f(null);
    }

    public void logWithMsg() {
        KLog.d(LOG_MSG);
        KLog.i(LOG_MSG);
        KLog.w(LOG_MSG);
        KLog.e(LOG_MSG);
        KLog.f(LOG_MSG);
    }

    public void logWithTag() {
        KLog.d(TAG, LOG_MSG);
        KLog.i(TAG, LOG_MSG);
        KLog.w(TAG, LOG_MSG);
        KLog.e(TAG, LOG_MSG);
        KLog.f(TAG, LOG_MSG);
    }

    public void logWithLong() {
        KLog.d(TAG, STRING_LONG);
    }

    public void logWithParams() {
        KLog.d(TAG, LOG_MSG, "params1", "params2", this);
        KLog.i(TAG, LOG_MSG, "params1", "params2", this);
        KLog.w(TAG, LOG_MSG, "params1", "params2", this);
        KLog.e(TAG, LOG_MSG, "params1", "params2", this);
        KLog.f(TAG, LOG_MSG, "params1", "params2", this);
    }


    public void logWithJson() {
        KLog.json("12345");
        KLog.json(null);
        KLog.json(JSON);
    }

    public void logWithLongJson() {
        KLog.json(JSON_LONG);
    }

    public void logWithJsonTag() {
        KLog.json(TAG, JSON);
    }

    public void logWithFile() {
        KLog.file(getExternalCacheDir(), JSON_LONG);
        KLog.file(TAG, getExternalCacheDir(), JSON_LONG);
        KLog.file(TAG, getExternalCacheDir(), "test.txt", JSON_LONG);
    }

    public void logWithXml() {
        KLog.xml("12345");
        KLog.xml(null);
        KLog.xml(XML);
    }

    public void logWithXmlFromNet() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    String urlString = URL_XML;
                    URL url = new URL(urlString);
                    URLConnection urlConnection = url.openConnection();
                    if (urlConnection instanceof HttpURLConnection) {
                        connection = (HttpURLConnection) urlConnection;
                    }
                    if (connection != null) {
                        connection.setRequestMethod("GET");
                        connection.connect();
                        InputStream json_buffer = connection.getInputStream();
                        String jsonStr = inputStreamToString(json_buffer);
                        KLog.xml(jsonStr);
                    }
                } catch (IOException e) {
                    KLog.e(e.toString());
                } finally {
                    connection.disconnect();
                }

            }
        }).start();

    }

    private String inputStreamToString(InputStream inputStream) {
        StringBuffer buffer = new StringBuffer();
        InputStreamReader inputStreamReader;
        try {
            inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            // 释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }


    public String getPropertiesURL(Context c) {
        String url = null;
        Properties properties = new Properties();
        try {
            properties.load(getResourceManager().getRawFileEntry("resources/rawfile/config.prop").openRawFile());
            url = properties.getProperty("url");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return url;

    }

    /*
     * 浏览器
     * */
    private void initWeb(String urlString) {
        Intent intents = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withUri(Uri.parse(urlString))
                .withAction(IntentConstants.ACTION_SEARCH)
                .build();
        intents.setOperation(operation);
        startAbility(intents);
    }
}
